package io.terminus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author li.chunlong lcl253-137@alibaba-inc.com
 * @desc 公共字段自动填充处理类
 * @date 2021-09-22
 */
@Component
public class FieldAutoFillHandler implements MetaObjectHandler {

    /**
     * 插入策略
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 1、有对应字段才执行: 提高SQL执行性能，不用每张表的SQL都执行
        boolean hasCreateTimeSetter = metaObject.hasSetter("createTime");
        if (hasCreateTimeSetter) {
            strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
    }

    /**
     * 更新策略
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 2、字段没有赋值时才进行自动填充: 提高SQL执行性能，不用每次SQL都进行自动填充
        Object updateTimeField = getFieldValByName("updateTime", metaObject);
        if (Objects.isNull(updateTimeField)) {
            strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }
}
